<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Utils\ResponseResult\JsonResult;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class PermissionController extends Controller
{
    //保存权限
    public function save(Request $request)
    {
        //验证请求
        $rules=["data" => "required",];
        if(Validator::make($request->all(),$rules)->fails()){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        $data=$request->input("data");
        if(!$data){
            return JsonResult::forbidden(null,"请求参数错误");
        }
        //进行base64解码
        $data=base64_decode($data);
        //将json解码为数组
        $data=json_decode($data,true);

        DB::beginTransaction();
        try{
            DB::table("permissions")->delete();
            DB::table("permissions")->insert($data);
            return JsonResult::created(null,"保存权限成功");
        }catch (\Exception $e){
            DB::rollBack();
            return JsonResult::forbidden(null,"保存权限失败");
        }

    }
    public function get(Request $request)
    {
        $data = DB::table("permissions")->cursor()->toArray();
        $data=json_encode($data);
        $data = base64_encode($data);
        if(!$data){
            return JsonResult::forbidden(null, "获取参数失败！");
        }
        return JsonResult::success($data, "获取权限成功！");
    }
}
